﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.ComponentModel;
using System.Data;
using System.Data.Objects;

namespace RL
{
    /// <summary>
    /// Логика взаимодействия для wRouteListItem.xaml
    /// </summary>
    public partial class wRouteListItem : Window
    {
        RL.routelistEntities routelistEntities;
        private RouteListLogic RLL;
        public routelistEntities ContextDB
        {
            get { 
                return (routelistEntities)GetValue(ContextDBProperty);
            }
            set { 
                SetValue(ContextDBProperty, value);
                //ucSelectPerson1.DBContext = value;
                RLL.ContextDB = value;
                //ucScheduleRL1.ContextDB = value;
                //ucInfoRL1.ContextDB = value;
            }
        }

        // Using a DependencyProperty as the backing store for ContextDB.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty ContextDBProperty =
            DependencyProperty.Register("ContextDB", typeof(routelistEntities), typeof(wRouteListItem), new UIPropertyMetadata(null, new PropertyChangedCallback(propContext)));

        public static void propContext(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            wRouteListItem item = d as wRouteListItem;
            if (null == item) return;
            item.ucScheduleRL1.ContextDB = (routelistEntities)e.NewValue;
            item.ucInfoRL1.ContextDB = (routelistEntities)e.NewValue;
        }


        public RouteList RouteList
        {
            get { return (RouteList)GetValue(RouteListProperty); }
            set { 
                SetValue(RouteListProperty, value);
                mainRouteListGrid.DataContext = value;
                RLL.RouteList = value;
                labelSummVed.Content = string.Format("Сумма по вокзальным ведомостям: {0}",RLL.CalcVokzalTableSum());
                labelSumInsVed.Content = string.Format("Сумма страх. сбор: {0}", RLL.CalcVokzalTableInsurance());
            }
        }

        // Using a DependencyProperty as the backing store for RouteList.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty RouteListProperty =
            DependencyProperty.Register("RouteList", typeof(RouteList), typeof(wRouteListItem), new UIPropertyMetadata(null, new PropertyChangedCallback(propRouteList)));

        private static void propRouteList(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            wRouteListItem item = d as wRouteListItem;
            if (null == d) return;
            RouteList rl = e.NewValue as RouteList;
            if (null == rl) return;
        }



        public int RouteListID
        {
            get { return (int)GetValue(RouteListIDProperty); }
            set { SetValue(RouteListIDProperty, value); }
        }

        // Using a DependencyProperty as the backing store for RouteListID.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty RouteListIDProperty =
            DependencyProperty.Register("RouteListID", typeof(int), typeof(wRouteListItem), new UIPropertyMetadata(0, new PropertyChangedCallback(propRouteListID)));


        public static void propRouteListID(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            wRouteListItem item = d as wRouteListItem;
            if (null == item) return;
            if (null == item.ContextDB) return;
            int val = (int)e.NewValue;
            item.RouteList = (from o in item.ContextDB.RouteList where o.id == val select o).FirstOrDefault();
        }

        public wRouteListItem()
        {
            InitializeComponent();
            RLL = new RouteListLogic();
            if (System.ComponentModel.DesignerProperties.GetIsInDesignMode(this)) return;
            ContextDB = new routelistEntities();
        }

        //public bool Contains(object vt)
        //{
        //    if (null == RouteList) return false;
        //    VokzalTable item = vt as VokzalTable;
        //    if (null == item) return false;
        //    return (item.id_routelist == RouteList.id);
        //}

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {


            routelistEntities = new RL.routelistEntities();
            // Загрузить данные в VokzalTable. Можно изменить этот код как требуется.
            RefreshVokzalTable();
        }

        private void RefreshVokzalTable()
        {
            System.Windows.Data.CollectionViewSource vokzalTableViewSource = ((System.Windows.Data.CollectionViewSource)(this.FindResource("vokzalTableViewSource")));
            //System.Data.Objects.ObjectQuery<RL.VokzalTable> vokzalTableQuery = this.GetVokzalTableQuery(routelistEntities);
            //vokzalTableViewSource.Source = vokzalTableQuery.Execute(System.Data.Objects.MergeOption.AppendOnly);
            vokzalTableViewSource.Source = this.GetVokzalTableQuery(routelistEntities);
            //vokzalTableViewSource.View.Filter += new Predicate<object>(Contains);
            vokzalTableViewSource.View.Refresh();
        }

        private void buttonOK_Click(object sender, RoutedEventArgs e)
        {
            SaveData();
            try
            {
                DialogResult = true;
            }
            catch (Exception)
            {
            }
        }

        private void buttonPrint_Click(object sender, RoutedEventArgs e)
        {
            ListReportRL rp_data = new ListReportRL();
            rp_data.Add(RLL.GetRLTable());
            Form1 wnd = new Form1();
            wnd.ReportData = rp_data;
            wnd.Show();
        }

        private bool IsModified()
        {
            bool bResult = false;
            if (null == ContextDB) return false;
            bResult = ContextDB.ObjectStateManager.GetObjectStateEntries(System.Data.EntityState.Added).Count() > 0 || ContextDB.ObjectStateManager.GetObjectStateEntries(System.Data.EntityState.Deleted).Count() > 0 || ContextDB.ObjectStateManager.GetObjectStateEntries(System.Data.EntityState.Modified).Count() > 0;
            return bResult;
        }

        private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            if (IsModified())
            {
                var result = MessageBox.Show("Сохранить изменения?", "Предупреждение", MessageBoxButton.YesNoCancel, MessageBoxImage.Exclamation, MessageBoxResult.Yes);
                switch (result)
                {
                    case MessageBoxResult.Yes:
                        if (false == SaveData())
                        {
                            e.Cancel = true;
                        }
                        else
                        {
                            try
                            {
                                DialogResult = true;
                            }
                            catch (Exception)
                            {
                            }
                        }
                        break;
                    case MessageBoxResult.Cancel:
                        e.Cancel = true;
                        break;
                }

            }
        }

        private bool SaveData()
        {
            bool bResult = true;
            try
            {
                ContextDB.SaveChanges();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString(), Properties.Resources.DataSavingError, MessageBoxButton.OK, MessageBoxImage.Exclamation);
                bResult = false;
            }
            return bResult;
        }

        private void buttonLoad_Click(object sender, RoutedEventArgs e)
        {
            DateTime dt;

            if (null == ContextDB) return;
            if (null == RouteList) return;
            //if (false == DateTime.TryParse(RouteList.datedoc, out dt))
            //{
            //    MessageBox.Show("Ошибка анализа даты документа.");
            //    return;
            //}
            App app = (App)App.Current;
            dt = RouteList.dt_datedoc.HasValue ? RouteList.dt_datedoc.Value : app.WorkDate;

            if (!RouteList.nomdeparture.HasValue)
            {
                MessageBox.Show("Не указан номер выхода");
                return;
            }
            ObjectQuery<RouteTable> rt = RLL.getSchedule(RouteList.nomdeparture.Value, dt);
            if (rt.Count() != 1)
            {
                MessageBox.Show("Ошибка при определении расписания движения. Возможно нет информации о номере выхода, или для одного дня недели введено несколько расписаний. ");
                return;
            }
            RouteTable rt_item = rt.FirstOrDefault();
            if (null == rt_item)
            {
                MessageBox.Show("Ошибка при определении расписания.");
                return;
            }
            RLL.LoadRouteTable(rt_item.id);
            SaveData();
            ucScheduleRL1.RouteList = RouteList;
            ucInfoRL1.RouteList = RouteList;
        }

        //private ObjectQuery<VokzalTable> GetVokzalTableQuery(routelistEntities routelistEntities)
        //{
        //    // Автоматически созданный код
        //    System.Data.Objects.ObjectQuery<RL.VokzalTable> vokzalTableQuery = routelistEntities.VokzalTable;
           
        //    // Для явной загрузки данных, возможно, потребуется добавить методы Include, аналогичные показанным ниже:
        //    // vokzalTableQuery = vokzalTableQuery.Include("VokzalTable.RouteList").
        //    // Дополнительные сведения см. по ссылке http://go.microsoft.com/fwlink/?LinkId=157380
        //    // Возвращает ObjectQuery.
        //    return vokzalTableQuery;
        //}
        private IEnumerable<VokzalTable> GetVokzalTableQuery(routelistEntities routelistEntities)
        {
            // Автоматически созданный код
            int id_routelist = 0;
            if (null != RouteList)
            {
                id_routelist = RouteList.id;
            }
            var vokzalTableQuery = from o in routelistEntities.VokzalTable where o.id_routelist == id_routelist select o;

            // Для явной загрузки данных, возможно, потребуется добавить методы Include, аналогичные показанным ниже:
            // vokzalTableQuery = vokzalTableQuery.Include("VokzalTable.RouteList").
            // Дополнительные сведения см. по ссылке http://go.microsoft.com/fwlink/?LinkId=157380
            // Возвращает ObjectQuery.
            return vokzalTableQuery;
        }

        private void vokzalTableDataGrid_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            System.Windows.Data.CollectionViewSource vokzalTableViewSource = ((System.Windows.Data.CollectionViewSource)(this.FindResource("vokzalTableViewSource")));
            VokzalTable vtbl = vokzalTableViewSource.View.CurrentItem as VokzalTable;
            if (vtbl == null) return;
            wStationMoneyTable wnd = new wStationMoneyTable();
            wnd.VokzalTableID = vtbl.id;
            int old_idroutelist = vtbl.id_routelist;
            //wnd.ContextDB = ContextDB;
            //wnd.VokzalTable = item;
            if (true == wnd.ShowDialog())
            {
                //vokzalTableViewSource.View.Refresh();
                routelistEntities.Refresh(System.Data.Objects.RefreshMode.StoreWins, vtbl);
                if (vtbl.id_routelist != old_idroutelist)
                {
                    RefreshVokzalTable();
                }
                else
                {
                    
                }
            }
        }

    }
}
